package com.example.demo.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.demo.config.annotation.Token;
import com.example.demo.config.config.ErrorCode;
import com.example.demo.config.config.WebException;
import com.example.demo.model.SysUser;
import com.example.demo.service.SysUserService;
import com.example.demo.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.method.HandlerMethod;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Optional;

public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token

        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)object;
        Method method = handlerMethod.getMethod();

//        httpServletResponse.setCharacterEncoding( "UTF-8");
//        httpServletResponse.setContentType( "application/json; charset=utf-8");




        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(Token.class)) {
            Token userLoginToken = method.getAnnotation(Token.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new WebException(ErrorCode.LACK_OF_TOKEN, "无token，请重新登录");
                }
                // 获取 token 中的 user id
                Integer userId;
                try {
                    userId = tokenService.getUserId(token);
                } catch (JWTDecodeException j) {
                    throw new WebException(ErrorCode.TOKEN_DECODE_FAILED, "Token解析失败");
                }
                Optional<SysUser> user = sysUserService.findById(userId);
                if (!user.isPresent()) {
                    throw new WebException(ErrorCode.NO_USER_FOUND, "用户不存在，请重新登录");
                }
                // 验证 token
                try {
                    tokenService.verify(user.get(), token);
                } catch (JWTVerificationException e) {
                    throw new WebException(ErrorCode.TOKEN_VERIFY_FAILED, "Token验证失败");
                }
                return true;
            }
        }



        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // 如果不是映射到方法直接通过
        if(!(o instanceof HandlerMethod)){
            return;
        }
        HandlerMethod handlerMethod = (HandlerMethod)o;
        Method method = handlerMethod.getMethod();


        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        //每次通过成功处理的请求都会记录登录时间和ip，请求错误不会经过这里
        Integer userId = tokenService.getUserId(token);
        Optional<SysUser> oUser = sysUserService.findById(userId);
        if(!oUser.isPresent()){ //找不到用户，说明被删除
            return;
        }
        //记录并更新登录时间和ip
        SysUser user = oUser.get();
        user.setLastLoginIp(httpServletRequest.getRemoteAddr());
        user.setLastLoginTime(Timestamp.valueOf(LocalDateTime.now()));
        sysUserService.save(user);
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
